package com.b2b.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页信息
 */
public class PageInfoBean<T> implements Serializable
{
	private static final long serialVersionUID = 1L;
	
	private static final int DEFAULT_PAGE_NUM = 1;
	
	private static final int DEFAULT_PAGE_SIZE = 10;

	// 当前页
	private int pageNum = 0;

	// 每页的数量
	private int pageSize = 0;

	// 当前页的数量
	private int size = 0;

	// 总记录数
	private long total = 0;

	// 总页数
	private int pages = 0;

	// 结果集
	private List<T> list;
	
	@Override
	public String toString()
	{
		return String.format("{pageNum: [%s], pageSize: [%s], size: [%s], total: [%s], pages: [%s], list: %s}", this.pageNum, this.pageSize, this.size, this.total, this.pages, new ArrayList<T>(this.list));
	}
	
	public PageInfoBean()
	{
		super();
	}

	public PageInfoBean(int pageNum, int pageSize, long total)
	{
		super();
		this.pageNum = pageNum;
		this.pageSize = pageSize;
		this.total = total;
		
		setPageCount();
	}

	public int getPageNum()
	{
		return pageNum;
	}

	public void setPageNum(int pageNum)
	{
		this.pageNum = pageNum;
	}

	public int getPageSize()
	{
		return pageSize;
	}

	public void setPageSize(int pageSize)
	{
		this.pageSize = pageSize;
	}

	public int getSize()
	{
		return size;
	}

	public void setSize(int size)
	{
		this.size = size;
	}

	public long getTotal()
	{
		return total;
	}

	public void setTotal(long total)
	{
		this.total = total;
	}

	public int getPages()
	{
		return pages;
	}

	public void setPages(int pages)
	{
		this.pages = pages;
	}

	public List<T> getList()
	{
		return list;
	}

	public void setList(List<T> list)
	{
		this.list = list;
	}

	/**
	 * 设置总页数
	 */
	public void setPageCount()
    {
		if (pageSize > 0) {
            pages = (int) (total / pageSize + ((total % pageSize == 0) ? 0 : 1));
        } else {
            pages = 0;
        }
    }
	
	/**
	 * 设置分页后的列表
	 */
	public void setSubList(int pageNum, int pageSize, List<T> list)
	{
		if(pageNum < DEFAULT_PAGE_NUM)
		{
			pageNum = DEFAULT_PAGE_NUM;
		}
		
		if(pageSize == 0)
		{
			pageSize = DEFAULT_PAGE_SIZE;
		}
		
		setPageNum(pageNum);
		
		setPageSize(pageSize);
		
		if(list == null || list.size() == 0)
		{
			return;
		}
		
		setTotal(list.size());
		
		setPageCount();
		
		int fromIndex = (pageNum - 1) * pageSize;
		if(fromIndex >= total)
		{
			return;
		}
		int toIndex = (int) (pageNum * pageSize >= total ? total : pageNum * pageSize);
		List<T> subList = list.subList(fromIndex, toIndex);
		if(subList == null || subList.size() == 0)
		{
			return;
		}
		
		this.list = subList;
		this.size = subList.size();
	}
	
	/**
	 * 设置结果集和当前页的数量
	 */
	public void setListAndSize(List<T> list)
	{
		if(list == null || list.size() == 0)
		{
			return;
		}
		
		this.list = list;
		this.size = list.size();
	}
	
}